package com.yungu.swift.utils;

import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author Zerrion
 */
public class MapUtils {

    private MapUtils() {
    }

    public static Map<String, Object> build() {
        return build(16);
    }

    public static Map<String, Object> build(int length) {
        return new HashMap<>(length);
    }

    public static Map<String, Object> build(String key, Object value) {
        Map<String, Object> map = build(2);
        map.put(key, value);
        return map;
    }

    public static Map<String, Object> build(String[] keyArray, Object[] valueArray) {
        Map<String, Object> map = build(Math.max((int) (keyArray.length / .75f) + 1, 16));
        for (int i = 0; i < keyArray.length; i++) {
            map.put(keyArray[i], valueArray[i]);
        }
        return map;
    }

    public static Map<String, Object> keyUnderscore2Camel(Map<String, Object> map) {
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();
        Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            map.put(entry.getKey(), StringUtils.underscore2Camel(String.valueOf(entry.getValue())));
        }
        return map;
    }

    public static Map<String, Object> convertObjToMap(Object obj) {
        Map<String, Object> resultMap = build();
        List<Field> fieldList = buildFieldList(obj.getClass(), null);
        if (CollectionUtils.isNotEmpty(fieldList)) {
            try {
                for (Field field : fieldList) {
                    field.setAccessible(true);
                    Object o = field.get(obj);
                    resultMap.put(field.getName(), o);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    private static List<Field> buildFieldList(Class<?> aClass, List<Field> fieldList) {
        if (CollectionUtils.isEmpty(fieldList)) {
            fieldList = new ArrayList<>();
        }
        fieldList.addAll(Arrays.asList(aClass.getDeclaredFields()));
        Class<?> superclass = aClass.getSuperclass();
        if (superclass.equals(Object.class)) {
            return fieldList;
        }
        buildFieldList(superclass, fieldList);
        return fieldList;
    }
}
